<template>
  <view class="compression">
    <canvas
      class="canvas"
      :style="{ width: cw0 + 'px', height: ch0 + 'px' }"
      canvas-id="myCanvas0"
      id="myCanvas0"
    />
  </view>
</template>

<script>
import config from '../../ossConfig.js'
import uploadImage from '../../utils/uploadAliyun.js'

export default {
  name: 'Compression',
  props: {
    filePath: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      cw0: '',
      ch0: ''
    }
  },
  methods: {
    takeImage(filePath) {
      const _self = this
      uploadImage({
        filePath: filePath,
        dir: 'OXPHOTO/',
        success: function(res) {
			// debugger
          _self.$emit('finishCom', config.uploadImageUrl + res)
          uni.hideLoading()
        },
        fail: function(res) {
          uni.hideLoading()
          console.log('上传失败', res)
        }
      })
    },
    async compression(filePath, size) {
		// debugger
      uni.showLoading({ mask: true })
      const _self = this

      if (size < 1000) {
        _self.takeImage(filePath)
        return false
      }

      try {
        // 使用uni-app的压缩API
        const [error, res] = await uni.compressImage({
          src: filePath,
          quality: 80
        })

        if (error) {
          console.log('压缩失败', error)
          _self.takeImage(filePath)
          return false
        }

        _self.takeImage(res.tempFilePath)
        return false
      } catch (err) {
        console.log('压缩失败', err)
        _self.takeImage(filePath)
        return false
      }

      // 获取图片信息
      // 检查图片信息是否可访问
      try {
        const [error, res] = await uni.getImageInfo({
          src: filePath
        })

        if (error) {
          console.error(error)
          return
        }

        const originHeight = res.height
        const originWidth = res.width
        // 最大尺寸限制
        const maxLength = getApp().globalData.windowWidth
        // 目标尺寸
        const targetWidth = maxLength
        const targetHeight = Math.round(originHeight * maxLength / originWidth)
        // 更新canvas大小
        const maxWH = targetWidth > targetHeight ? targetWidth : targetHeight
        let x = 0
        let y = 0
        const w = targetWidth
        const h = targetHeight
        let rode = 0

        // 矫正摄像方向
        switch (res.orientation) {
          case 'down':
            rode = 180
            break
          case 'left':
            rode = 270
            break
          case 'right':
            rode = 90
            break
        }

        if (rode) {
          this.cw0 = maxWH
          this.ch0 = maxWH
        } else {
          this.cw0 = w
          this.ch0 = h
        }

        const ctx = uni.createCanvasContext('myCanvas0', this)
        ctx.clearRect(0, 0, w, h)

        if (rode) {
          x = -w / 2
          y = -h / 2
          ctx.translate(w / 2, h / 2)
          ctx.rotate(rode * Math.PI / 180)
        }

        ctx.drawImage(res.path, x, y, w, h)
        ctx.draw(false, () => {
          clearTimeout(this.st)
          this.st = setTimeout(() => {
            uni.canvasToTempFilePath({
              canvasId: 'myCanvas0',
              fileType: 'jpg',
              quality: 0.2,
              success: (res) => {
                _self.takeImage(res.tempFilePath)
              },
              fail: (err) => {
                console.error(err)
              }
            }, this)
            uni.hideLoading()
          }, parseInt(size) / 2)
        })
      } catch (err) {
        console.error(err)
        uni.hideLoading()
      }
    }
  }
}
</script>

<style>
.canvas {
  position: absolute;
  z-index: -99999;
  left: -99999px;
}
</style>